﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace General.Core.Common.OAuth.WeChat
{
    public class WeChatHelper
    {
        public WeChatHelper()
        {
        }

        /// <summary>
        /// 根据AppID和AppSecret获得access token(默认过期时间为2小时)
        /// </summary>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> GetAccessToken()
        {
            //获得配置信息
            //oauth_config config = oauth_helper.get_config(2);
            string send_url = WeChatDefaults.AccessTokenEndpoint
                + "?appid=" + WeChatDefaults.AppId
                + "&secret=" + WeChatDefaults.AppSecret
                + "&code=CODE&grant_type=authorization_code";
            //发送并接受返回值
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetStringAsync(send_url);
                if (string.IsNullOrEmpty(result.Result) && (result.Result.Contains("errmsg") || result.Result.Contains("errmsg")))
                {
                    return null;
                }
                try
                {
                    Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result.Result);
                    return dic;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 取得临时的Access Token(默认过期时间为2小时)
        /// </summary>
        /// <param name="code">临时Authorization Code</param>
        /// <param name="state">防止CSRF攻击，成功授权后回调时会原样带回</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> GetAccessToken(string code, string state)
        {
            string send_url = WeChatDefaults.AccessTokenEndpoint
                + "?appid=" + WeChatDefaults.AppId
                + "&secret=" + WeChatDefaults.AppSecret
                + "&code=" + code
                + "&state=" + state
                + "&grant_type=authorization_code";
            //发送并接受返回值
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetStringAsync(send_url);
                if (string.IsNullOrEmpty(result.Result) && (result.Result.Contains("errmsg") || result.Result.Contains("errmsg")))
                {
                    return null;
                }
                try
                {
                    Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result.Result);
                    return dic;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 根据access_token判断access_token是否过期
        /// </summary>
        /// <param name="access_token"></param>
        /// <returns>true表示未失效</returns>
        public static bool CheckAccessToken(string access_token)
        {
            string send_url = WeChatDefaults.AccessTokenEndpoint + "?access_token=" + access_token + "&openid=" + string.Empty;
            //发送并接受返回值
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetStringAsync(send_url);
                if (!string.IsNullOrEmpty(result.Result) && !(result.Result.Contains("errmsg") || result.Result.Contains("errmsg")))
                {
                    try
                    {
                        Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result.Result);
                        if (dic.ContainsKey("errmsg"))
                        {
                            if (dic["errmsg"].ToString() == "ok")
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        return false;
                    }
                    catch
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 若fresh_token已过期则根据refresh_token取得新的refresh_token
        /// </summary>
        /// <param name="refresh_token">refresh_token</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> GetRefreshToken(string refresh_token)
        {
            string send_url = WeChatDefaults.RefreshTokenEndpoint
                + "?appid=" + WeChatDefaults.AppId
                + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            //发送并接受返回值
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetStringAsync(send_url);
                if (!string.IsNullOrEmpty(result.Result) && !(result.Result.Contains("errmsg") || result.Result.Contains("errmsg")))
                {
                    return null;
                }
                try
                {
                    Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result.Result);
                    return dic;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 获取登录用户自己的基本资料
        /// </summary>
        /// <param name="access_token">临时的Access Token</param>
        /// <param name="open_id">用户openid</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> GetUserInfo(string access_token, string open_id)
        {
            //发送并接受返回值 
            string send_url = WeChatDefaults.UserInformationEndpoint + "?access_token=" + access_token + "&openid=" + open_id;
            //发送并接受返回值
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetStringAsync(send_url);
                if (!string.IsNullOrEmpty(result.Result) && !(result.Result.Contains("errmsg") || result.Result.Contains("errmsg")))
                {
                    return null;
                }
                Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result.Result);
                return dic;
            }
        }
    }


}
